package com.peng.herostory.cmdhanlder;

import com.peng.herostory.Broadcaster;
import com.peng.herostory.model.User;
import com.peng.herostory.model.UserManager;
import com.peng.herostory.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UserEntryCmdHandler implements ICmdHandler<GameMsgProtocol.UserEntryCmd> {
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserEntryCmd cmd) {
        // 获取用户 Id
        Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();
        if (null == userId) {
            return;
        }
        // 获取已有用户
        User existUser = UserManager.getUserById(userId);
        if (null == existUser) {
            log.error("用户不存在, userId = {}", userId);
            return;
        }
        // 获取英雄形象
        String heroAvatar = existUser.getHeroAvatar();

        GameMsgProtocol.UserEntryResult userEntryResult = GameMsgProtocol.UserEntryResult.newBuilder().setUserId(userId).setHeroAvatar(heroAvatar).build();
        Broadcaster.broadcast(userEntryResult);
    }
}
